﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Innovative.ProXr
{
	/// <summary>
	/// Provides a set of methods to manipulate byte data from and to the
	/// relay device
	/// </summary>
	public static class RelayByteExtensions
	{
		public static RelayByte[] CreateRange(this RelayByte[] target, byte low, byte high)
		{
			RelayByte[] returnValue = new RelayByte[high - low + 1];
			int j = 0;

			for (byte i = low; i < high; i++)
			{
				returnValue[j] = i;
				j++;
			}

			return returnValue;
		}

		public static RelayByte[][] CreateRange(this RelayByte[][] target, int totalCount, byte low, byte high)
		{
			RelayByte[][] returnValue = new RelayByte[32][];
		
			for (int k = 0; k < totalCount; k++)
			{
				int j = 0;
				returnValue[k] = new RelayByte[high - low + 1];

				for (byte i = low; i < high; i++)
				{
					returnValue[k][j] = i;
					j++;
				}
			}

			return returnValue;
		}

		/// <summary>
		/// Appends one RelayByte to the end of a RelayByte array.
		/// </summary>
		/// <param name="target">Target RelayByte array</param>
		/// <param name="source">RelayByte value to append to the array</param>
		/// <returns>A new combined RelayByte array containing the value of the source
		/// appended to the end of the target RelayByte array</returns>
		public static RelayByte[] AppendByte(this RelayByte[] target, RelayByte source)
		{
			RelayByte[] returnValue = new RelayByte[target.Length + 1];

			target.CopyTo(returnValue, 0);
			returnValue[returnValue.Length - 1] = source;

			return returnValue;
		}

		/// <summary>
		/// Appends one RelayByte array to another RelayByte array.
		/// </summary>
		/// <param name="target">Target RelayByte array</param>
		/// <param name="source">Source RelayByte array</param>
		/// <returns>A new combined byte array containing the values of the source RelayByte
		/// array appended to the end of the target RelayByte array</returns>
		public static RelayByte[] AppendBytes(this RelayByte[] target, RelayByte[] source)
		{
			RelayByte[] returnValue = new RelayByte[target.Length + source.Length];

			Array.Copy(target, returnValue, target.Length);
			Array.Copy(source, 0, returnValue, target.Length, source.Length);

			return returnValue;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="bytes"></param>
		/// <returns></returns>
		public static byte[] ToByteArray(this RelayByte[] bytes)
		{
			byte[] returnValue = new byte[0];

			// ***
			// *** Query the byte value from the array
			// ***
			var qry = from tbl in bytes
					  where tbl != null
					  select tbl.Value;

			// ***
			// *** Convert the query result to an array
			// ***
			returnValue = qry.ToArray();

			return returnValue;
		}
	}
}
